<?php
namespace app\manage\controller;

use app\manage\controller\Base;
use think\facade\Db;
use support\View;
use support\Request;
use app\model\DownloadModel;

class DownloadController extends Base
{
    public function index(Request $request)
    {
		$data=$request->get();
		if(!isset($data['key'])){
			$data['key']='';
		}
        View::assign('data', $data);
		$info=DownloadModel::where('title', 'like', '%'.$data['key'].'%')
		->order('id desc')
		->paginate(['list_rows'=>10,'query'=>request()->all()]);
        View::assign('info', $info);
        View::assign('count1', $info->total());
        return view('download/index');
    }
    public function ajax(Request $request)
    {
        $data=$request->post();
        $download=new DownloadModel();
        if ($data['type']=='download_del') {
            if ($download->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='download_all') {
            if ($download->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
		if($data['type']=='download_start'){
			if($download->where('id',$data['id'])->update(['isopen'=>1])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
		if($data['type']=='download_stop'){
			if($download->where('id',$data['id'])->update(['isopen'=>0])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
        return json(['code'=>0]);
    }
    public function add(Request $request)
    {
        if (request()->method()=='POST') {
            $data=$request->post();
            $validate = new \app\manage\validate\DownloadValidate;
            if (!$validate->check($data)) {
                return view_e($validate->getError());
            }

            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            $file = $request->file('file');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if($file->getSize() > 10*1024*1024){return view_e('附件大小不能超过10M');}
                $path = '/download/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['file']=$path;
            }else{
                return view_e('请添加附件！');
            }

            $file = $request->file('pic');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/download/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['pic']=$path;
            }


            if ($data['desc']=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags($data['text'])), 0, 200);
            }
			
			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
			$config=Db::name('config')->column('value', 'key');
			//压缩图片
			foreach ($arr[1] as $k=>$v) {
			    if (substr($v, 0, 4)!='http' and is_file(substr($v, 1))) {
			        $newarr=getimagesize(substr($v, 1));
				   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
				      $image = \think\Image::open(substr($v, 1));
				      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
				      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
							
				   }
			    }
			}
            $data['faid']=session('uid');
            if (DownloadModel::create($data)) {
                return '<script>alert("你好，添加成功了！");parent.location.reload()</script>';
            } else {
                return view_e('添加失败了');
            }
        }
        return view('download/add');
    }
    public function edit(Request $request)
    {
        if (request()->method()=='POST') {
            $data=$request->post();
            $validate = new \app\manage\validate\DownloadValidate;
            if (!$validate->scene('edit')->check($data)) {
                return view_e($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            if ($data['desc']=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags($data['text'])), 0, 200);
            }

            $file = $request->file('file');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if($file->getSize() > 10*1024*1024){return view_e('附件大小不能超过10M');}
                $path = '/download/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['file']=$path;
            }

            $file = $request->file('pic');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/download/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['pic']=$path;
            }



			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
			$config=Db::name('config')->column('value', 'key');
			//压缩图片
			foreach ($arr[1] as $k=>$v) {
			    if (substr($v, 0, 4)!='http' and is_file(substr($v, 1))) {
			        $newarr=getimagesize(substr($v, 1));
				   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
				      $image = \think\Image::open(substr($v, 1));
				      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
				      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
				   }
			    }
			}
            $res=DownloadModel::update($data, ['id' => $data['id']]);
            if ($res) {
                return view_s('修改成功', url('download/index',['st'=>1]));
            } else {
                return view_e('修改失败了');
            }
        }
        $cid=$request->input('id',0);
        $data=Db::name('download')->where('id', $cid)->find();
        View::assign('data', $data);
        return view('download/edit');
    }
}
